package com.xu.springboot04.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Controller
@Slf4j
public class FormController {

    @GetMapping("/form_layouts")
    public String form_layouts(){
        return "form/form_layouts";
    }

    /**
     * MultipartFile 自动封装上传过来的文件
     */
    @PostMapping("/upload")
    public String upload(@RequestParam("email") String email,
                         @RequestParam("username") String username,
                         @RequestPart("avatar") MultipartFile avatar,
                         @RequestPart("photos") MultipartFile[] photos){
        log.info("上传的信息：email={}, username={}, avatar={}, photos={}",
                    email, username, avatar.getSize(), photos.length);

        if (!avatar.isEmpty()){
            String filename = avatar.getOriginalFilename();
            // 保存到文件服务器，OSS 服务器
            try {
                avatar.transferTo(new File("F:\\cache\\" + filename));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (photos.length > 0){
            for (MultipartFile photo : photos) {
                if (!photo.isEmpty()){
                    try {
                        photo.transferTo(new File("F:\\cache\\" + photo.getOriginalFilename()));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        return "main";
    }
}
